<template>
  <div>
    <!-- 查询与操作按钮 -->
    <div class="card" style="margin-bottom: 5px; display: flex; align-items: center;">
      <el-input v-model="searchTrackingNumber" prefix-icon="Search" style="width: 240px; margin-right: 10px;" placeholder="请输入物流单号查询"></el-input>
      <el-select v-model="searchStatus" clearable placeholder="请选择订单状态" style="width: 150px; margin-right: 10px;">
        <el-option label="未发货" value="0"></el-option>
        <el-option label="已发货" value="1"></el-option>
        <el-option label="已完成" value="2"></el-option>
      </el-select>
      <el-button type="info" plain @click="loadOrdersByFilters">查询</el-button>
      <el-button type="warning" plain @click="reset">重置</el-button>
    </div>

    <!-- 订单列表 -->
    <el-table :data="orders" border stripe style="width: 100%;">
      <el-table-column prop="goodsId" label="商品ID" width="80"></el-table-column>
      <el-table-column prop="description" label="商品描述"></el-table-column>
      <el-table-column label="商品图片">
        <template #default="scope">
          <img :src="scope.row.image" alt="商品图片" style="width: 50px; height: 50px; display:block;">
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="60"></el-table-column>
      <el-table-column prop="recipientName" label="收件人姓名"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
      <el-table-column prop="shippingAddress" label="收货地址"></el-table-column>
      <el-table-column prop="trackingNumber" label="物流单号"></el-table-column>
      <el-table-column prop="logisticsCompany" label="物流公司"></el-table-column>
      <el-table-column prop="shippedAt" label="发货时间">
        <template #default="scope">
          {{ formatDate(scope.row.shippedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" type="primary" :icon="Edit" @click="openEditDialog(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑订单" v-model="editDialogVisible" width="30%">
      <el-form :model="editingOrder" label-width="100px">
        <el-form-item label="状态">
          <el-select v-model="editingOrder.statusText" placeholder="请选择状态">
            <el-option label="未发货" value="0"></el-option>
            <el-option label="已发货" value="1"></el-option>
            <el-option label="已完成" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="editingOrder.trackingNumber" placeholder="请输入物流单号"></el-input>
        </el-form-item>
        <el-form-item label="物流公司">
          <el-input v-model="editingOrder.logisticsCompany" placeholder="请输入物流公司"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrderDetails">确定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination" style="text-align: center; margin-top: 20px;">
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="totalItems">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request.js'; // 确保这是你的axios封装
import { Edit } from '@element-plus/icons-vue';

const searchTrackingNumber = ref('');
const searchStatus = ref('');
const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const editDialogVisible = ref(false);
const editingOrder = ref({});

// 加载订单列表
const loadOrders = async (pageNum = 1, trackingNumber = '', status = '') => {
  try {
    const res = await request.get('/pointsOrder/page', {
      params: {
        pageNum,
        pageSize: pageSize.value,
        trackingNumber,
        status
      }
    });
    if (res.code === '200') {
      orders.value = res.data.list.map(order => ({
        ...order,
        statusText: order.status.toString()
      })) || [];
      totalItems.value = res.data.total;
    }
  } catch (error) {
    console.error('Failed to load orders:', error);
  }
};

// 根据过滤条件加载订单
const loadOrdersByFilters = () => {
  currentPage.value = 1; // 重置当前页为第一页
  loadOrders(1, searchTrackingNumber.value, searchStatus.value);
};

// 重置搜索条件
const reset = () => {
  searchTrackingNumber.value = '';
  searchStatus.value = '';
  loadOrders();
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadOrders(newPage, searchTrackingNumber.value, searchStatus.value);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化状态
const formatStatus = (status) => {
  switch (status) {
    case 0:
      return '未发货';
    case 1:
      return '已发货';
    case 2:
      return '已完成';
    default:
      return '未知';
  }
};

// 打开编辑对话框
const openEditDialog = (order) => {
  editingOrder.value = {
    id: order.id,
    statusText: order.status.toString(),
    trackingNumber: order.trackingNumber,
    logisticsCompany: order.logisticsCompany
  };
  editDialogVisible.value = true;
};

// 保存订单详情（包括状态、物流单号和物流公司）
const saveOrderDetails = async () => {
  try {
    const res = await request.put('/pointsOrder/update', {
      id: editingOrder.value.id,
      status: parseInt(editingOrder.value.statusText),
      trackingNumber: editingOrder.value.trackingNumber,
      logisticsCompany: editingOrder.value.logisticsCompany
    });
    if (res.code === '200') {
      editDialogVisible.value = false;
      loadOrders(currentPage.value, searchTrackingNumber.value, searchStatus.value); // 刷新订单列表
    } else {
      console.error('Failed to update order details:', res.message);
    }
  } catch (error) {
    console.error('Failed to update order details:', error);
  }
};

// 初始化加载订单列表
onMounted(() => {
  console.log('Component mounted, loading orders...');
  loadOrders();
});
</script>

<style scoped>
.pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
